package com.hundsun.yr.universal.library.base;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.gyf.barlibrary.ImmersionBar;
import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.common.KeyBoardUtils;
import com.hundsun.yr.universal.library.common.SmartBarUtils;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.loading.VaryViewHelperController;
import com.hundsun.yr.universal.library.netstatus.NetChangeObserver;
import com.hundsun.yr.universal.library.netstatus.NetStateReceiver;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.widget.HSToast;

import de.greenrobot.event.EventBus;

@TargetApi(Build.VERSION_CODES.KITKAT) 
public abstract class BaseAppCompatActivity extends AppCompatActivity{
	
	/**
	 * 自定义Toast
	 */
	private HSToast hsToast;

	/**
     * Log tag
     */
    protected String TAG_LOG = null;

    /**
     * 屏幕信息
     */
    protected int mScreenWidth = 0;
    protected int mScreenHeight = 0;
    protected float mScreenDensity = 0.0f;

    protected Context mContext = null;
    
    /**
     * 网络状态
     */
    protected NetChangeObserver mNetChangeObserver = null;

    /**
     * 加载试图容器
     */
    private VaryViewHelperController mVaryViewHelperController = null;

    /**
     * 跳转动画方式
     */
    public enum TransitionMode {
        LEFT, RIGHT, TOP, BOTTOM, SCALE, FADE
    }
    
    
    protected int configTheme() {
        return 0;
    }
    
    

    private int theme = 0;// 当前界面设置的主题

    public ImmersionBar mImmersionBar;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (toggleOverridePendingTransition()) {
            switch (getOverridePendingTransitionMode()) {
                case LEFT:
                    overridePendingTransition(R.anim.left_in,R.anim.left_out);
                    break;
                case RIGHT:
                    overridePendingTransition(R.anim.right_in,R.anim.right_out);
                    break;
                case TOP:
                    overridePendingTransition(R.anim.top_in,R.anim.top_out);
                    break;
                case BOTTOM:
                    overridePendingTransition(R.anim.bottom_in,R.anim.bottom_out);
                    break;
                case SCALE:
                    overridePendingTransition(R.anim.scale_in,R.anim.scale_out);
                    break;
                case FADE:
                    overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
                    break;
            }
        }
        
        if (savedInstanceState == null) {
            theme = configTheme();
            
        }else{
        	theme = savedInstanceState.getInt("theme");
        }
        
        // 设置主题
        if (theme > 0){
        	setTheme(theme);
        }
        
        super.onCreate(savedInstanceState);
        // base setup
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }

        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this);
        }
        SmartBarUtils.hide(getWindow().getDecorView());
//        setTranslucentStatus(isApplyStatusBarTranslucency());

        mContext = this;
        TAG_LOG = this.getClass().getSimpleName();
        BaseAppManager.getInstance().addActivity(this);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        mScreenDensity = displayMetrics.density;
        mScreenHeight = displayMetrics.heightPixels;
        mScreenWidth = displayMetrics.widthPixels;

        if (getContentViewLayoutID() != 0) {
        	
        	setContentView(getContentViewLayoutID());
        	
        } else {
            throw new IllegalArgumentException("You must return a right contentView layout resource Id");
        }

        mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                super.onNetConnected(type);
                onNetworkConnected(type);
            }

            @Override
            public void onNetDisConnect() {
                super.onNetDisConnect();
                onNetworkDisConnected();
            }
        };

        NetStateReceiver.registerObserver(mNetChangeObserver);

        if (null != getLoadingTargetView()) {
        	mVaryViewHelperController = new VaryViewHelperController(getLoadingTargetView());
        }
//        requestData();
        //初始化沉浸式
        initImmersionBar();
        initViewsAndEvents();
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this).statusBarDarkFont(true).flymeOSStatusBarFontColor(R.color.black);
        mImmersionBar.init();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	// TODO Auto-generated method stub
    	super.onSaveInstanceState(outState);
    	
    	 outState.putInt("theme", theme);
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	
    	if (theme != configTheme()) {
    		reload();
        } 
    }
    
    /**
     * 重启Activity
     */
    public void reload() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();

        overridePendingTransition(0, 0);
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
        	KeyBoardUtils.getInstance(this).hide();//键盘弹出的请款先隐藏再finish防止动画卡顿
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }
    
    @Override
    public void finish() {
        super.finish();
        BaseAppManager.getInstance().removeActivity(this);
        if (toggleOverridePendingTransition()) {
            switch (getOverridePendingTransitionMode()) {
                case LEFT:
                    overridePendingTransition(R.anim.left_in,R.anim.left_out);
                    break;
                case RIGHT:
                    overridePendingTransition(R.anim.right_in,R.anim.right_out);
                    break;
                case TOP:
                    overridePendingTransition(R.anim.top_in,R.anim.top_out);
                    break;
                case BOTTOM:
                    overridePendingTransition(R.anim.bottom_in,R.anim.bottom_out);
                    break;
                case SCALE:
                    overridePendingTransition(R.anim.scale_in,R.anim.scale_out);
                    break;
                case FADE:
                    overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetStateReceiver.removeRegisterObserver(mNetChangeObserver);
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this);
        }
        mImmersionBar.destroy();
    }

    /**
     * 当前Activity的布局文件
     *
     * @return id of layout resource
     */
    protected abstract int getContentViewLayoutID();
    /**
     * 初始化view并且绑定监听
     */
    protected abstract void initViewsAndEvents();
    
    /**
     * 获取bundle数据
     *
     * @param extras
     */
    protected abstract void getBundleExtras(Bundle extras);

    /**
     * 当 eventbus 事件传递过来时调用
     *
     * @param eventCenter
     */
    @SuppressWarnings("rawtypes")
	protected abstract void onEveComming(EventCenter eventCenter);

    /**
     * 是否绑定eventbus
     *
     * @return
     */
    protected abstract boolean isBindEventBusHere();
    /**
     * 获取绑定loading的视图
     */
    protected abstract View getLoadingTargetView();
    
    /**
     * 加载数据
     */
//    protected abstract void requestData();

    /**
     * 网络连接
     */
    protected abstract void onNetworkConnected(NetUtils.NetType type);

    /**
     * 网络断开
     */
    protected abstract void onNetworkDisConnected();

    /**
     * 设置状态栏是否透明
     *
     * @return
     */
    protected abstract boolean isApplyStatusBarTranslucency();


    /**
     * 是否要跳转动画
     *
     * @return
     */
    protected abstract boolean toggleOverridePendingTransition();

    /**
     * 设置跳转动画枚举类型
     */
    protected abstract TransitionMode getOverridePendingTransitionMode();

    /**
     * 跳转Activity
     *
     * @param clazz
     */
    protected void readyGo(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    /**
     * 跳转Activity并传递bundle
     *
     * @param clazz
     * @param bundle
     */
    protected void readyGo(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 跳转Activity并关闭当前Activity
     *
     * @param clazz
     */
    protected void readyGoThenKill(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        finish();
    }
    

    /**
     * 跳转Activity并传递bundle再关闭当前Activity
     *
     * @param clazz
     * @param bundle
     */
    protected void readyGoThenKill(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    /**
     * 跳转Activity并获取返回值
     *
     * @param clazz
     * @param requestCode
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode) {
        Intent intent = new Intent(this, clazz);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 跳转Activity并获取返回值并传递bundle
     *
     * @param clazz
     * @param requestCode
     * @param bundle
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 弹出 Snackbar
     *
     * @param msg
     */
    protected void showSnackbar(String msg) {
        //防止遮盖虚拟按键
        if (null != msg && !TextUtils.isEmpty(msg)) {
            Snackbar.make(getLoadingTargetView(), msg, Snackbar.LENGTH_SHORT).show();
        }
    }
    
    
    /**
	 * 弹出Toast
	 * @param resId Toast文字资源ID
	 */
    protected void showToast(int resId) {
    	if(hsToast==null)hsToast=new HSToast(this);
    	hsToast.showSingletonToast(resId);
    }
    /**
	 * 弹出Toast
	 * @param text Toast文字内容
	 */
    protected void showToast(String text) {
    	if(text==null)return;
    	if(hsToast==null)hsToast=new HSToast(this);
    	hsToast.showSingletonToast(text);
    }
    

    /**
     * 显示loading视图
     *
     * @param toggle
     */
    protected void toggleShowLoading(boolean toggle, String msg) {
        if (null == mVaryViewHelperController) {
        	return;
//            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showLoading(msg);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示空视图
     *
     * @param toggle
     */
    protected void toggleShowEmpty(boolean toggle, int drawableRes,String msg, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
        	return;
//            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showEmpty(drawableRes,msg, onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示错误视图
     *
     * @param toggle
     */
    protected void toggleShowError(boolean toggle, String msg, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
        	return;
//            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showError(msg, onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示网络错误视图
     *
     * @param toggle
     */
    protected void toggleNetworkError(boolean toggle, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
        	
        	return;
//            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showNetworkError(onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }
    
    /**
     * 隐藏试图
     */
    public void toggleHide(){
    	
    	 if (null == mVaryViewHelperController) {
    		 return;
//             throw new IllegalArgumentException("You must return a right target view for loading");
         }
    	 mVaryViewHelperController.restore();
    }

    @SuppressWarnings("rawtypes")
	public void onEventMainThread(EventCenter eventCenter) {
        if (null != eventCenter) {
            onEveComming(eventCenter);
        }
    }

    /**
     * 设置状态栏背景Drawable
     *
     * @param tintDrawable
     */
    protected void setSystemBarTintDrawable(Drawable tintDrawable) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
//            if (tintDrawable != null) {
//                mTintManager.setStatusBarTintEnabled(true);
//                mTintManager.setTintDrawable(tintDrawable);
//            } else {
//                mTintManager.setStatusBarTintEnabled(false);
//                mTintManager.setTintDrawable(null);
//            }
//        }

    }

    /**
     * 设置状态栏状态
     *
     * @param on
     */
    protected void setTranslucentStatus(boolean on) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window win = getWindow();
//            WindowManager.LayoutParams winParams = win.getAttributes();
//            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//            if (on) {
//                winParams.flags |= bits;
//            } else {
//                winParams.flags &= ~bits;
//            }
//            win.setAttributes(winParams);
//        }
    }
    
    
    /**
     * 通过泛型来简化findViewById
     */
    @SuppressWarnings("unchecked")
	protected final <E extends View> E findView(int id) {
        try {
            return (E) findViewById(id);
        } catch (ClassCastException ex) {
            Log.e(TAG_LOG, "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }
    
    /**
     * 通过泛型来简化findViewById
     */
    @SuppressWarnings("unchecked")
	protected final <E extends View> E findView(View view,int id) {
        try {
            return (E) view.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e(TAG_LOG, "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

}
